/*
 * Copyright (C) 2011-present ShenZhen iBOXCHAIN Information Technology Co.,Ltd.
 *
 * All right reserved.
 *
 * This software is the confidential and proprietary
 * information of iBOXCHAIN Company of China.
 * ("Confidential Information"). You shall not disclose
 * such Confidential Information and shall use it only
 * in accordance with the terms of the contract agreement
 * you entered into with iBOXCHAIN inc.
 */
package com.example.wac.shiro;

import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Iterator;

/**
 * @author wuancheng
 * @description
 * @date 2023-04-14 18:27:00
 */

public class RestPathMatchingFilterChainResolver extends PathMatchingFilterChainResolver {
    private static final Logger log = LoggerFactory.getLogger(RestPathMatchingFilterChainResolver.class);

    public RestPathMatchingFilterChainResolver() {
    }

    @Override
    public FilterChain getChain(ServletRequest request, ServletResponse response, FilterChain originalChain) {
        FilterChainManager filterChainManager = this.getFilterChainManager();
        if (!filterChainManager.hasChains()) {
            return null;
        } else {
            String requestURI = this.getPathWithinApplication(request);
            String httpMethod = WebUtils.toHttp(request).getMethod();
            Iterator var8 = filterChainManager.getChainNames().iterator();

            String pathPattern;
            String[] pathPatternArray;
            do {
                do {
                    if (!var8.hasNext()) {
                        return null;
                    }

                    pathPattern = (String)var8.next();
                    pathPatternArray = pathPattern.split("@@");
                } while(!this.pathMatches(pathPatternArray[0], requestURI));
            } while(pathPatternArray.length > 1 && !httpMethod.equalsIgnoreCase(pathPatternArray[1]));

            if (log.isTraceEnabled()) {
                log.trace("Matched path pattern [" + pathPattern + "] for requestURI [" + requestURI + "].  " + "Utilizing corresponding filter chain...");
            }

            return filterChainManager.proxy(originalChain, pathPattern);
        }
    }
}

